package playnsimple.core.state;

import playn.core.CanvasImage;
import playn.core.ImageLayer;
import playn.core.PlayN;
import playn.core.Pointer;
import playnsimple.core.PlaynSimple;
import playnsimple.core.graphics.ImageStack;
import playnsimple.core.graphics.TextImage;
import playn.core.Font;


public class EndState extends BaseState {
    
    /*
     * Properties
     */
    private ImageLayer endImageLayer;

    /*
     * Constructor / State Methods
     */
    public EndState(String label) {
        super(label);
    }
    
    @Override
    public void enter() {
        endImageLayer = buildImageStackLayer();
        addListeners();
    }
    
    @Override
    public void update() {
    }
    
    @Override
    public void paint() {   
        PlayN.graphics().rootLayer().add(endImageLayer);
    }
    
    /*
     * Additional Methods
     */
    private ImageLayer buildImageStackLayer() {
        TextImage gameOver = new TextImage("game over");
        gameOver.fontSize = 60;
        gameOver.fontStyle = Font.Style.BOLD;
        CanvasImage gameOverImage = gameOver.getImage();
        
        TextImage tapHere = new TextImage("(double tap to start over)");
        tapHere.fontSize = 16;
        CanvasImage tapHereImage = tapHere.getImage();
        
        ImageStack imageStack = new ImageStack(gameOverImage);
        imageStack.addToBottom(tapHereImage, 60); 
        
        ImageLayer imageStackLayer = imageStack.layer();
        float x = (PlayN.graphics().width() - imageStackLayer.width()) * .5f;
        float y = (PlayN.graphics().height() - imageStackLayer.height()) * .5f;
        imageStackLayer.setTranslation(x, y);
        
        return imageStackLayer;
    }
    
    private void addListeners() {         
        endImageLayer.addListener(new Pointer.Listener() {
            Long thisTapAt = 0L;
            Long lastTapAt = 0L;
            
            @Override
            public void onPointerStart(Pointer.Event event) {
                thisTapAt = System.currentTimeMillis(); 
                PlaynSimple.log("tap at: " + thisTapAt);
            }
            
            @Override
            public void onPointerEnd(Pointer.Event event) {
                if ( wasDoubleTap() ) {
                    machine.changeState("home");
                }
                lastTapAt = thisTapAt;
            }

            @Override
            public void onPointerDrag(Pointer.Event event) {
            }
            
            private Boolean wasDoubleTap() {
                Integer TAP_TIME_LIMIT = 200; // millisecond
                Long tapSpan = thisTapAt - lastTapAt;
                PlaynSimple.log("tap pause: " + tapSpan + " ms");
                return tapSpan < TAP_TIME_LIMIT;
            }
        });               
    }

}
